//
//  MyDraftViewController.m
//  eshow
//
//  Created by Hisoka on 16/1/10.
//  Copyright © 2016年 Hisoka. All rights reserved.
//

#import "MyDraftViewController.h"
#import "ESAlterShareView.h"
#import "MyResumeCollectionViewCell.h"
#import "ResumeEditViewController.h"

static NSString * const RESUME_CELL = @"resumeCell";

@interface MyDraftViewController ()<UIActionSheetDelegate, ESAlertShareViewDelegate, UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) NSArray *actionNameArr;
@property (nonatomic, strong) UIActionSheet *moreAS;
@property (nonatomic, strong) ESAlterShareView *shareV;
@property (nonatomic, strong) UIScrollView *resumeSV;
@property (nonatomic, strong) NSArray *resumeData;
@property (nonatomic, strong) UIPageControl *resumePC;
@property (nonatomic, strong) NSDictionary *currentResumeDic;
@property (nonatomic, assign) CGFloat svWidth;
@property (nonatomic, assign) CGFloat svHeight;
@property (nonatomic, strong) UICollectionView *thumbCV;
@property (nonatomic, strong) NSArray *heightArr;
@property (nonatomic, strong) NSString *devModel;
@property (nonatomic, strong) ResumeEditViewController *editVC;
@end

@implementation MyDraftViewController

- (void) viewWillAppear:(BOOL)animated {
    [self getResumeList];
}

- (void) viewWillDisappear:(BOOL)animated {
    [MobClick event:@"Click_MyDraft_backBTN"];

    [_shareV dismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDefine];
    
    [self getResumeList];
    [self setStyle];
}

#pragma mark - 初始化赋值
- (void) initDefine {
    
    [self customizeBackItem];
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _devModel = [[TMCache sharedCache] objectForKey:@"deviceModel"];
    
    if ([_devModel isEqualToString:@""] || _devModel == nil) _devModel = @"auto";
    
}

#pragma mark - 设置瀑布流样式
- (void) setCollectionViewStyle {
    self.view.backgroundColor = [UIColor whiteColor];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.thumbCV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) collectionViewLayout:flowLayout];
    
    _thumbCV.delegate = self;
    _thumbCV.dataSource = self;
    _thumbCV.backgroundColor = GRAY_COLOR;
    
    [self.view addSubview:_thumbCV];
    
    [_thumbCV registerClass:[MyResumeCollectionViewCell class] forCellWithReuseIdentifier:RESUME_CELL];
    
}

- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if ([_resumeData count] <= 0) {
        return 0;
    }else{
        return [_resumeData count];
    }
}

-(UIColor *) randomColor {
    CGFloat hue = ( arc4random() % 256 / 256.0 ); //0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0,away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; //0.5 to 1.0,away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyResumeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:RESUME_CELL forIndexPath:indexPath];
    
    cell.backgroundColor = [self randomColor];
    
    NSDictionary *tmpData = [_resumeData objectAtIndex:indexPath.row];
    
    NSInteger remainder = indexPath.row % 2;
    NSInteger currentRow = indexPath.row / 2;
    CGFloat   currentHeight = [[tmpData objectForKey:@"item_height"] floatValue];
    CGFloat colWidth = [[tmpData objectForKey:@"item_width"] floatValue];
    
    CGFloat positionX = colWidth * remainder + 14 * (remainder + 1);
    CGFloat positionY = (currentRow + 1) * 14;
    for (NSInteger i=0; i<currentRow; i++) {
        NSInteger position = remainder + i * 2;
        positionY += [[[_resumeData objectAtIndex:position] objectForKey:@"item_height"] floatValue];
    }
    
    cell.frame = CGRectMake(positionX, positionY, colWidth, currentHeight);
    
//    NSLog(@"x %f, y %f, w %f, h %f", positionX, positionY, colWidth, currentHeight);
    
    [cell.bgImg sd_setImageWithURL:[NSURL URLWithString:[tmpData objectForKey:@"thumb"]] placeholderImage:[UIImage imageNamed:@"loginBg"]];
    cell.titleLB.text = [tmpData objectForKey:@"tpl_name"];
    cell.dateLB.text = [tmpData objectForKey:@"created_time"];
    
    
    return cell;
}

// 定义每个collectionview 大小
- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *tmpData = [_resumeData objectAtIndex:indexPath.row];
    CGFloat colWidth = [[tmpData objectForKey:@"item_width"] floatValue];
    CGFloat rowHeight = [[tmpData objectForKey:@"item_height"] floatValue];
    return CGSizeMake(colWidth, rowHeight);
}

//定义每个 collectionview 纵向间距
- (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    _currentResumeDic = [_resumeData objectAtIndex:indexPath.row];
    
    [self showMoreActionSheet];
}

- (void) setStyle {
    self.view.backgroundColor = GRAY_COLOR;
    self.navigationItem.title = @"草稿箱";
    // 初始化分享浮层
    self.shareV = [[ESAlterShareView alloc] initWithShareView:self];
    
}

#pragma mark - 设置滑动内容
- (void) setResumeList {
    
    if (IS_IPHONE4) {
        _svWidth = ScreenWidth - 20;
        _svHeight = ceilf(_svWidth / 0.9);
    }else{
        _svWidth = ScreenWidth - 20;
        _svHeight = ceilf(_svWidth / 0.7);
    }
    
    self.resumeSV = [UIScrollView newAutoLayoutView];
    [self.view addSubview:_resumeSV];
    
    [_resumeSV autoPinToTopLayoutGuideOfViewController:self withInset:10];
    [_resumeSV autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view];
    [_resumeSV autoSetDimensionsToSize:CGSizeMake(ScreenWidth, _svHeight + 20)];
    _resumeSV.backgroundColor = [UIColor clearColor];
    
    for (int i = 0; i < [_resumeData count]; i++) {
        UIView *bgView = [[UIView alloc] init];
        bgView.frame = CGRectMake(ScreenWidth * i, 0, ScreenWidth, _svHeight + 20);
        
        UILabel *resumeTitleLB = [UILabel newAutoLayoutView];
        [bgView addSubview:resumeTitleLB];
        
        [resumeTitleLB autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:bgView];
        [resumeTitleLB autoAlignAxis:ALAxisVertical toSameAxisOfView:bgView];
        [resumeTitleLB autoSetDimensionsToSize:CGSizeMake(ScreenWidth, 20)];
        resumeTitleLB.backgroundColor = [UIColor clearColor];
        resumeTitleLB.textColor = [UIColor grayColor];
        resumeTitleLB.textAlignment = NSTextAlignmentCenter;
        resumeTitleLB.text = [[_resumeData objectAtIndex:i] objectForKey:@"tpl_name"];
        
        UIImageView *thumbImg = [UIImageView newAutoLayoutView];
        [bgView addSubview:thumbImg];
        
        CGFloat tmpRatio = [[[_resumeData objectAtIndex:i] objectForKey:@"ratio"] doubleValue];
        
        [thumbImg autoAlignAxis:ALAxisHorizontal toSameAxisOfView:bgView];
        [thumbImg autoAlignAxis:ALAxisVertical toSameAxisOfView:bgView];
        [thumbImg autoSetDimensionsToSize:CGSizeMake(_svWidth, _svWidth / tmpRatio)];
        thumbImg.layer.masksToBounds = YES;
        thumbImg.layer.cornerRadius = 5.0f;
        thumbImg.contentMode = UIViewContentModeScaleAspectFit;
        
        NSURL *imgUrl = [NSURL URLWithString:[[_resumeData objectAtIndex:i] objectForKey:@"thumb"]];
        
        if ([self isiPadModel:[[TMCache sharedCache] objectForKey:@"deviceModel"]] == YES) {
            [thumbImg sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"placeholderBgiP4"]];
        }else{
            [thumbImg sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"placeholderBg"]];
        }
        
//        [thumbImg sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"homeBg"]];
        
        [_resumeSV addSubview:bgView];
    }
    
    _resumeSV.contentSize = CGSizeMake(ScreenWidth * [_resumeData count], _svHeight);
    _resumeSV.contentOffset = CGPointMake(CGRectGetWidth(_resumeSV.frame), 0);
    _resumeSV.pagingEnabled = YES;
    _resumeSV.showsHorizontalScrollIndicator = NO;
    _resumeSV.showsVerticalScrollIndicator = NO;
    _resumeSV.delegate = self;
    
    self.resumePC = [UIPageControl newAutoLayoutView];
    [self.view addSubview:_resumePC];
    
    [_resumePC autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:_resumeSV withOffset:5];
    [_resumePC autoAlignAxis:ALAxisVertical toSameAxisOfView:_resumeSV];
    [_resumePC autoSetDimensionsToSize:CGSizeMake(_svWidth, 20)];
    _resumePC.currentPageIndicatorTintColor = ORANGE_COLOR;
    _resumePC.pageIndicatorTintColor = [UIColor grayColor];
    _resumePC.numberOfPages = [_resumeData count];
    _resumePC.currentPage = 0;
    _currentResumeDic = [_resumeData objectAtIndex:0];
}

- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger page = floor((_resumeSV.contentOffset.x - ScreenWidth / 2) / ScreenWidth) + 1;
    _currentResumeDic = [_resumeData objectAtIndex:page];
    _resumePC.currentPage = page;
}

#pragma mark - 获取简历列表
- (void) getResumeList {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[[TMCache sharedCache] objectForKey:@"SSID"] forKey:@"ssid"];
    [parameters setObject:@"2" forKey:@"type"];
    [parameters setObject:_devModel forKey:@"device"];
    
    [SVProgressHUD show];
    [[HttpManager instance] requestWithMethod:@"User/getResumeList"
                                   parameters:parameters
                                      success:^(NSDictionary *result) {
                                          
                                          NSDictionary *tmpData = [result objectForKey:@"data"];
                                          _resumeData = [tmpData objectForKey:@"list"];
                                          
                                          [[TMCache sharedCache] setObject:[tmpData objectForKey:@"user"] forKey:@"userInfo"];
                                          
                                          if ([_resumeData count] <= 0) {
                                              UILabel *defaultLB = [UILabel newAutoLayoutView];
                                              [self.view addSubview:defaultLB];
                                              
                                              [defaultLB autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.view];
                                              [defaultLB autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view];
                                              [defaultLB autoSetDimensionsToSize:CGSizeMake(150, 30)];
                                              defaultLB.backgroundColor = [UIColor clearColor];
                                              defaultLB.textAlignment = NSTextAlignmentCenter;
                                              defaultLB.text = @"暂无相关内容";
                                              defaultLB.textColor = [UIColor grayColor];
                                          }else{
                                              
                                              if ([_resumeData count] > 6) {
                                                  if (_thumbCV == NULL) {
                                                      [self setCollectionViewStyle];
                                                  }else{
                                                      [_thumbCV reloadData];
                                                  }
                                              }else{
                                                  if (_thumbCV != NULL) [_thumbCV removeFromSuperview];
                                                  
                                                  if (_resumeSV != NULL) {
                                                      [_resumeSV removeFromSuperview];
                                                      [_resumePC removeFromSuperview];
                                                  }
                                                  
                                                  self.navigationItem.rightBarButtonItem.enabled = YES;
                                                  UIButton *editBTN = [self customizedRightButton];
                                                  [editBTN addTarget:self action:@selector(showMoreActionSheet) forControlEvents:UIControlEventTouchUpInside];
                                                  self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:editBTN];
                                                  [self setResumeList];
                                              }
                                          }
                                          
                                          [SVProgressHUD dismiss];
                                      }
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                          [SVProgressHUD showInfoWithStatus:[error localizedDescription] maskType:SVProgressHUDMaskTypeBlack];
                                      }];
}

#pragma mark - 显示更多选项
- (void) showMoreActionSheet {
    [MobClick event:@"Click_MyDraft_moreBTN"];

    self.actionNameArr = @[@"编辑", @"删除"];
    self.moreAS = [[UIActionSheet alloc] initWithTitle:nil
                                              delegate:self
                                     cancelButtonTitle:@"取消"
                                destructiveButtonTitle:nil
                                     otherButtonTitles:nil];
    [_actionNameArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [_moreAS addButtonWithTitle:obj];
    }];
    
    _moreAS.destructiveButtonIndex = 1;
    
    [_moreAS showInView:self.view];
}

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        [MobClick event:@"Click_MyDraft_cancelBTN"];
        return;
    }
    
    switch (buttonIndex) {
//        case 1:
//            _shareV.shareUrl = [_currentResumeDic objectForKey:@"share_url"];
//            [_shareV show];
//            break;
        case 1:
            [MobClick event:@"Click_MyDraft_editBTN"];
            self.editVC = [[ResumeEditViewController alloc] init];
            _editVC.resumeType = @"draft";
            _editVC.navTitle = @"草稿编辑";
            _editVC.resumeUrl = [_currentResumeDic objectForKey:@"edit_url"];
            [self.navigationController pushViewController:_editVC animated:YES];
            break;
        case 2:
            [MobClick event:@"Click_MyDraft_delBTN"];
            [self delResume];
            break;
        default:
            break;
    }
    
}

#pragma mark - 删除简历
- (void) delResume {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[[TMCache sharedCache] objectForKey:@"SSID"] forKey:@"ssid"];
    [parameters setObject:_devModel forKey:@"device"];
    [parameters setObject:@"2" forKey:@"type"];
    [parameters setObject:[_currentResumeDic objectForKey:@"rid"] forKey:@"rid"];
    
    [SVProgressHUD show];
    [[HttpManager instance] requestWithMethod:@"User/delResume"
                                   parameters:parameters
                                      success:^(NSDictionary *result) {
                                          
                                          NSDictionary *tmpData = [result objectForKey:@"data"];
                                          _resumeData = [tmpData objectForKey:@"list"];
                                          
                                          [[TMCache sharedCache] setObject:[tmpData objectForKey:@"user"] forKey:@"userInfo"];
                                          
                                          if ([_resumeData count] <= 0) {
                                              
                                              if (_resumeSV != NULL) {
                                                  [_resumePC removeFromSuperview];
                                                  [_resumeSV removeFromSuperview];
                                              }
                                              
                                              self.navigationItem.rightBarButtonItem.enabled = NO;
                                              UILabel *defaultLB = [UILabel newAutoLayoutView];
                                              [self.view addSubview:defaultLB];
                                              
                                              [defaultLB autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.view];
                                              [defaultLB autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view];
                                              [defaultLB autoSetDimensionsToSize:CGSizeMake(150, 30)];
                                              defaultLB.backgroundColor = [UIColor clearColor];
                                              defaultLB.textAlignment = NSTextAlignmentCenter;
                                              defaultLB.text = @"暂无相关内容";
                                              defaultLB.textColor = [UIColor grayColor];
                                          }else{

                                              if ([_resumeData count] > 6) {
                                                  if (_thumbCV == NULL) {
                                                      [self setCollectionViewStyle];
                                                  }else{
                                                      [_thumbCV reloadData];
                                                  }
                                              }else{
                                                  if (_thumbCV != NULL) [_thumbCV removeFromSuperview];
                                                  
                                                  if (_resumeSV != NULL) {
                                                      [_resumeSV removeFromSuperview];
                                                      [_resumePC removeFromSuperview];
                                                  }
                                                  
                                                  self.navigationItem.rightBarButtonItem.enabled = YES;
                                                  UIButton *editBTN = [self customizedRightButton];
                                                  [editBTN addTarget:self action:@selector(showMoreActionSheet) forControlEvents:UIControlEventTouchUpInside];
                                                  self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:editBTN];
                                                  
                                                  [self setResumeList];
                                              }
                                          }
                                          
                                          [SVProgressHUD dismiss];
                                      }
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                          [SVProgressHUD showInfoWithStatus:[error localizedDescription] maskType:SVProgressHUDMaskTypeBlack];
                                      }];
}

- (BOOL) isiPadModel:(NSString *)model {
    
    if ([model rangeOfString:@"iPhone4"].location != NSNotFound) return YES;
    
    if ([model rangeOfString:@"iPod"].location != NSNotFound) return YES;
    
    if ([model rangeOfString:@"iPad"].location != NSNotFound) return YES;
    
    return NO;
}

- (UIButton *)customizedRightButton {
    UIImage *imgage=[UIImage imageNamed:@"editMoreICON"];
    UIButton *button=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, imgage.size.width + 0, imgage.size.height)];
    [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [button setImage:imgage forState:UIControlStateNormal];
    return button;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
